package com.fiveChess;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * database records of Game
 */
public class GameProvider extends ContentProvider {
	private SQLiteOpenHelper mOpenHelper;

	private static final int GAMES = 1;
	private static final int GAMES_ID = 2;
	private static final UriMatcher sURLMatcher = new UriMatcher(
			UriMatcher.NO_MATCH);

	static {
		sURLMatcher.addURI("com.fiveChess", "game", GAMES);
		sURLMatcher.addURI("com.fiveChess", "game/#", GAMES_ID);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "fiveChess.db";
		private static final int DATABASE_VERSION = 1;

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE "+Game.TABLE_NAME+" (" 
					+ "_id INTEGER PRIMARY KEY,"
					+ Game.Columns.CONTENT_GAME_CONTENT + " VARCHAR,"
					+ Game.Columns.CONTENT_TIME + " LONG,"
					+ Game.Columns.CONTENT_ENDED + " INTEGER,"
					+ Game.Columns.CONTENT_ISBLACK + " INTEGER);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion,
				int currentVersion) {
			if (true)
				Log.v("gongzhihui1990",
						"Upgrading "+Game.TABLE_NAME+" database from version " + oldVersion
								+ " to " + currentVersion
								+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + Game.TABLE_NAME);
			onCreate(db);
		}
	}

	public GameProvider() {
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri url, String[] projectionIn, String selection,
			String[] selectionArgs, String sort) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

		// Generate the body of the query
		int match = sURLMatcher.match(url);
		switch (match) {
		case GAMES:
			qb.setTables(Game.TABLE_NAME);
			break;
		case GAMES_ID:
			qb.setTables(Game.TABLE_NAME);
			qb.appendWhere("_id=");
			qb.appendWhere(url.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}

		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor ret = qb.query(db, projectionIn, selection, selectionArgs, null,
				null, sort);

		if (ret == null) {
			if (true)
				Log.v("gongzhihui1990", "Game.query: failed");
		} else {
			ret.setNotificationUri(getContext().getContentResolver(), url);
		}

		return ret;
	}

	@Override
	public String getType(Uri url) {
		int match = sURLMatcher.match(url);
		switch (match) {
		case GAMES:
			return "vnd.android.cursor.dir/game";
		case GAMES_ID:
			return "vnd.android.cursor.item/game";
		default:
			throw new IllegalArgumentException("Unknown URL");
		}
	}

	@Override
	public int update(Uri url, ContentValues values, String where,
			String[] whereArgs) {
		int count;
		long rowId = 0;
		int match = sURLMatcher.match(url);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		switch (match) {
		
		case GAMES_ID: {
			String segment = url.getPathSegments().get(1);
			rowId = Long.parseLong(segment);
			System.err.println("update _id:"+match);
			count = db.update(Game.TABLE_NAME, values, "_id=" + rowId, null);
			break;
		}
		default: {
			throw new UnsupportedOperationException("Cannot update URL: " + url);
		}
		}
		Log.v("gongzhihui1990", "*** notifyChange() rowId: " + rowId + " url "
				+ url);
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	@Override
	public Uri insert(Uri url, ContentValues initialValues) {
		if (sURLMatcher.match(url) != GAMES) {
			throw new IllegalArgumentException("Cannot insert into URL: " + url);
		}

		ContentValues values = new ContentValues(initialValues);

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = db.insert(Game.TABLE_NAME, Game.Columns.CONTENT_GAME_CONTENT,
				values);
		if (rowId < 0) {
			throw new SQLException("Failed to insert row into " + url);
		}

		Uri newUrl = ContentUris
				.withAppendedId(Game.Columns.CONTENT_URI, rowId);
		getContext().getContentResolver().notifyChange(newUrl, null);
		return newUrl;
	}

	public int delete(Uri url, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (sURLMatcher.match(url)) {
		case GAMES:
			count = db.delete("alarms", where, whereArgs);
			break;
		case GAMES_ID:
			String segment = url.getPathSegments().get(1);
			if (TextUtils.isEmpty(where)) {
				where = "_id=" + segment;
			} else {
				where = "_id=" + segment + " AND (" + where + ")";
			}
			count = db.delete("games", where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Cannot delete from URL: " + url);
		}

		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}
}
